import axios from "axios";
import Cookies from "js-cookie";
// import Qs from "qs";
import Base64 from "../util/Base64";
import router from "../router/index";
import { loginByUsername } from "@/api/login";
let sevoes = axios.create({
  // baseURL: "http://192.168.1.99:8080/m.api",
  baseURL: "http://192.168.1.188:8080/m.api",
  // baseURL: "http://39.108.158.69:8821/m.api",
  timeout: 15000,
});

// 2.1请求拦截//请求前附令牌
sevoes.interceptors.request.use(
  (config) => {
    config.headers.ADMINTOKEN = Cookies.get("data"); //附令牌到请求头
    return config;
  },
  (error) => Promise.reject(error)
);

// 2.2响应拦截
sevoes.interceptors.response.use(
  async (response) => {
    if (response.data.errno == 10006 || response.data.errno == 10001 ||response.data.errno ==10003) {
      //10006是"管理员尚未登录,没有令牌
      if (Cookies.get("checked") == "true") {
        await loginByUsername({//刷新令牌
          username: Base64.decode(Cookies.get("username")),
          password: Base64.decode(Cookies.get("password")),
          verifyCode: Base64.decode(Cookies.get("verifyCode")),
        }).then((res) => {
          console.log(res);
          var inFifteenMinutes = new Date(
            new Date().getTime() + 20 * 60 * 1000
          );
          Cookies.set("data", res.data.data, { expires: inFifteenMinutes }); //存储令牌
        });
        return sevoes(response.config);//重点，重新调用请求拦截
      } else {
        router.push("/login");
      }
    }
    return response;
  },
  (error) => {
    return Promise.resolve(error.response);
  }
);

export default sevoes;
